package homework;

/**
 * @author DCSGO
 * @version 1.0
 * 将字符串中指定部分进行反转
 * 例如: 将"abcdef"反转为“aedcbf"
 */
public class Homework01 {
    public static String reverse2(String str, int start, int end) {
        StringBuilder front = new StringBuilder(str.substring(0, start));
        StringBuilder reverseString = new StringBuilder(str.substring(start, end + 1));
        StringBuilder rear = new StringBuilder(str.substring(end + 1, str.length()));
        reverseString.reverse();

        return front.append(reverseString.append(rear)).toString();
    }

    public static String reverse1(String str, int start, int end) {
        if (str != null && start >= 0 && end > start && end < str.length()) {
            char[] chars = str.toCharArray();
            int left = start;
            int right = end;
            while (left < right) {
                char tmp = chars[left];
                chars[left] = chars[right];
                chars[right] = tmp;
                left++;
                right--;
            }
            return new String(chars);
        } else {
            throw new RuntimeException("传入参数有误!");
        }
    }

    public static void main(String[] args) {
        String str = "abcdef";
        System.out.println("before: " + str);
        try {
            str = reverse1(str, 1, 4);
            System.out.println("after: " + str);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //before: abcdef
        //after: aedcbf
    }
}
